<template>
  <div>

    <!-- 搜索栏 -->
    <search-bar @onSearch="onSearch" />
    <!-- /搜索栏 -->

    <el-button-group class="ml-4">
      <div class="header">
        <el-button type="primary" style="float: left;" @click="$router.push('/itemAdd')">新增商品</el-button>
      <el-upload
        style="float: right;"
        action="#"
        accept=".xlsx, .xls"
        :before-upload="readXlsx"
      >
        <el-button type="primary">批量导入</el-button>
      </el-upload>
      </div>
    </el-button-group>
    <a href="javascript:;" @click="excel" >下载模板</a>

    <el-table v-loading="loading" :data="itemList" :header-cell-style="{ 'background': '#f8f8f9', height: '50px' }">
      <el-table-column prop="itemName" label="商品名"  />
      <el-table-column prop="price" label="价格">
        <template #default="{row}">
          <el-tag type="warning">
            ￥{{ row.price }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="描述">
        <template #default="{row}">
          <el-tooltip
            class="box-item"
            effect="dark"
            placement="bottom"
          >
            <template #content>
              <div :style="{width: '500px'}">
                {{ row.desc }}
              </div>
            </template>
            <span>
              {{ row.desc.substr(0, 15) + '...' }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="sale" label="销量">
        <template #default="{row}">
          <el-tag>
            {{ row.sale }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onsale" label="上下架">
        <template #default="{ row }">
          <el-switch inline-prompt
            @change="switchItemState(row.id, row.onsale)"
            v-model="row.onsale"
            active-text="上架"
            inactive-text="下架" />
        </template>
      </el-table-column>
      <el-table-column prop="thumb" label="封面">
        <template #default="{ row }">
          <el-image preview-teleported style="width: 40px;height: 40px;border-radius: 50%;" :src="row.thumb"
            :preview-src-list="[row.thumb]" />
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="上架时间" />
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button type="primary" text  @click="handleUpdate( row.id )">编辑</el-button>
          <el-button type='danger' text @click="handleDelete( row.id )">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination layout="prev, pager, next, jumper, sizes"
     v-model:page-size="pageSize"

     v-model:current-page="page"
      :total="total" />
    <!-- /分页 -->
  </div>
</template>

<script>
import { listItem, addItems, updateItem, delItem } from '@/api/itemList/itemList.js'
import SearchBar from '@/components/SearchBar.vue'
import { utils, writeFileXLSX, read } from 'xlsx'
export default {
  name: 'ItemList',
  data () {
    return {
      // 遮罩层
      loading: true,
      total: 0,
      page: 1,
      pageSize: 10,
      itemList: [],
      // 查询参数
      searchParams: {}
    }
  },

  created () {
    this.getItemList()
  },

  components: {
    SearchBar
  },

  methods: {
    handleUpdate (id) {
      // 跳转到商品详情
      this.$router.push({
        path: '/itemUpdate',
        query: {
          id
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      this.$confirm('此操作会彻底删除该数据,继续吗?', '删除').then(() => {
        delItem(row.id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1000,
              onClose: () => {
                this.getItemList()
              }
            })
          }
        })
      })
    },

    /** 获取商品列表数据 */
    getItemList () {
      listItem({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        if (res.data.code === 200) {
          this.itemList = res.data.data.list
          this.total = res.data.data.total
          this.loading = false
        }
      })
    },

    // 行内点击开关修改商品上下架
    switchItemState (id, onsale) {
      updateItem({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },

    excel () {
      // 点击下载excel模板
      const excelData = [
        {
          商品名: 'xxx',
          价格: 0,
          描述: ''
        }
      ]
      const ws = utils.json_to_sheet(excelData)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品模板.xlsx')
    },

    readXlsx (file) {
      // 读取xlsx 解析成 数组json
      // 将文件 解析成 arrayBuffer
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onload = () => {
        // 文件读取完成触发 结果 在 fd.result属性上
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const _data = data.map(el => {
          return {
            itemName: el.商品名,
            price: el.价格,
            desc: el.描述
          }
        })
        // 调用 批量新增商品接口
        addItems({
          items: _data
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg,
              duration: 1000,
              onClose: () => {
                this.getItemList()
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg,
              duration: 1000
            })
          }
        })
      }

      return false
    },

    // 点击搜索
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.getItemList()
    }
  },

  watch: {
    // 监听当前页 和 一页多少条 重新发送请求 实现分页数据处理
    page () {
      this.getItemList()
    },
    pageSize () {
      this.getItemList()
    }
  }
}
</script>

<style lang="scss" scoped>
.header{
  width: 200px;
}
a{
  float: right;
  list-style: none;
  color: red;
}
</style>
